<template>
  <div class="notification-page">
    <n-card class="notification-card">
      <template #header>
        <div class="card-header">
          <h2>通知中心</h2>
          <div class="header-actions">
            <n-button 
              v-if="hasUnreadNotifications" 
              type="primary" 
              size="small" 
              @click="handleMarkAllAsRead"
            >
              全部已读
            </n-button>
            <n-button 
              type="error" 
              size="small" 
              :disabled="selectedIds.length === 0"
              @click="handleDeleteSelected"
            >
              删除选中
            </n-button>
            <n-button 
              type="default" 
              size="small" 
              @click="handleRefresh"
              :loading="loading"
            >
              刷新
            </n-button>
          </div>
        </div>
      </template>

      <!-- 通知列表 -->
      <div v-if="loading && notifications.length === 0" class="loading-container">
        <n-skeleton :rows="5" animated />
      </div>

      <div v-else-if="error" class="error-container">
        <n-result icon="error" title="加载失败" :description="error">
          <template #footer>
            <n-button type="primary" @click="handleRefresh">重试</n-button>
          </template>
        </n-result>
      </div>

      <div v-else-if="notifications.length === 0" class="empty-container">
        <n-empty description="暂无通知" />
      </div>

      <div v-else class="notification-list">
        <div class="list-header">
          <n-checkbox 
            v-model:checked="selectAll" 
            :indeterminate="isIndeterminate"
            @update:checked="handleSelectAll"
          >
            全选
          </n-checkbox>
          <span class="total-count">共 {{ total }} 条通知</span>
        </div>

        <div class="list-content">
          <div 
            v-for="notification in notifications" 
            :key="notification.id"
            class="notification-item"
            :class="{ 'unread': notification.status === 0 }"
          >
            <div class="item-left">
              <n-checkbox 
                v-model:checked="selectedIds" 
                :value="notification.id"
                @update:checked="handleSelectionChange"
              />
              <div class="notification-icon">
                 <n-icon v-if="notification.type === 0" color="#67C23A"><CheckmarkCircle /></n-icon>
                 <n-icon v-else-if="notification.type === 1" color="#F56C6C"><CloseCircle /></n-icon>
                 <n-icon v-else-if="notification.type === 2" color="#E6A23C"><WarningOutline /></n-icon>
                <n-icon v-else color="#409EFF"><InformationCircle /></n-icon>
              </div>
            </div>
            
            <div class="item-content" @click="handleNotificationClick(notification)">
              <div class="notification-header">
                <h4 class="notification-title">{{ notification.title }}</h4>
                <div class="notification-meta">
                  <n-tag 
                     v-if="notification.status === 0" 
                     type="primary" 
                     size="small"
                   >
                     未读
                   </n-tag>
                  <span class="notification-time">{{ formatTime(notification.createTime) }}</span>
                </div>
              </div>
              <p class="notification-text">{{ notification.content }}</p>
              <div v-if="notification.taskId && notification.taskType" class="notification-task">
                <n-tag size="small" type="info">
                  {{ getTaskTypeLabel(notification.taskType) }}
                </n-tag>
              </div>
            </div>
            
            <div class="item-actions">
               <n-button 
                 v-if="notification.status === 0" 
                 text 
                 size="small"
                 @click.stop="handleMarkAsRead(notification.id)"
               >
                 标记已读
               </n-button>
              <n-button 
                text 
                size="small" 
                style="color: var(--n-error-color)"
                @click.stop="handleDelete(notification.id)"
              >
                删除
              </n-button>
            </div>
          </div>
        </div>

        <!-- 分页 -->
        <div class="pagination-container">
          <n-pagination
            v-model:page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            show-size-picker
            show-quick-jumper
            @update:page="handleCurrentChange"
            @update:page-size="handleSizeChange"
          />
        </div>
      </div>
    </n-card>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMessage, useDialog } from 'naive-ui'
import { 
  CheckmarkCircle, 
  CloseCircle, 
  WarningOutline, 
  InformationCircle 
} from '@vicons/ionicons5'
import { useNotificationManager } from '../../notification/composables/useNotificationManager'
import type { Notification } from '../../../types/notification'

const router = useRouter()
const message = useMessage()
const dialog = useDialog()

// 使用通知管理器
const {
  notifications,
  loading,
  error,
  currentPage,
  pageSize,
  total,
  hasUnreadNotifications,
  fetchNotifications,
  markAsRead,
  markAllAsRead,
  deleteNotifications,
  refresh
} = useNotificationManager()

// 选择相关
const selectedIds = ref<number[]>([])
const selectAll = ref(false)
const isIndeterminate = computed(() => {
  return selectedIds.value.length > 0 && selectedIds.value.length < notifications.value.length
})

// 处理全选
const handleSelectAll = (value: boolean) => {
  if (value) {
    selectedIds.value = notifications.value.map(n => n.id)
  } else {
    selectedIds.value = []
  }
}

// 处理选择变化
const handleSelectionChange = () => {
  selectAll.value = selectedIds.value.length === notifications.value.length
}

// 处理标记全部已读
const handleMarkAllAsRead = async () => {
  try {
    await markAllAsRead()
    message.success('已将所有通知标记为已读')
    selectedIds.value = []
  } catch (error) {
    message.error('标记全部已读失败')
  }
}

// 处理标记单个已读
const handleMarkAsRead = async (id: number) => {
  try {
    await markAsRead(id)
    // 从选中列表中移除
    const index = selectedIds.value.indexOf(id)
    if (index > -1) {
      selectedIds.value.splice(index, 1)
    }
  } catch (error) {
    message.error('标记已读失败')
  }
}

// 处理删除通知
const handleDelete = async (id: number) => {
  try {
    dialog.warning({
      title: '提示',
      content: '确定要删除这条通知吗？',
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await deleteNotifications([id])
        message.success('删除成功')
        
        // 从选中列表中移除
        const index = selectedIds.value.indexOf(id)
        if (index > -1) {
          selectedIds.value.splice(index, 1)
        }
      }
    })
  } catch (error) {
    message.error('删除失败')
  }
}

// 处理删除选中通知
const handleDeleteSelected = async () => {
  try {
    dialog.warning({
      title: '提示',
      content: `确定要删除选中的 ${selectedIds.value.length} 条通知吗？`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: async () => {
        await deleteNotifications(selectedIds.value)
        message.success('删除成功')
        selectedIds.value = []
      }
    })
  } catch (error) {
    message.error('删除失败')
  }
}

// 处理刷新
const handleRefresh = async () => {
  await refresh()
}

// 处理页码变化
const handleCurrentChange = async (page: number) => {
  await fetchNotifications(page, true)
}

// 处理每页数量变化
const handleSizeChange = async (size: number) => {
  pageSize.value = size
  await fetchNotifications(1, true)
}

 // 处理通知点击
 const handleNotificationClick = async (notification: Notification) => {
   // 如果是未读通知，标记为已读
   if (notification.status === 0) {
     try {
       await markAsRead(notification.id)
     } catch (error) {
       console.error('标记通知为已读失败:', error)
     }
   }
   
   // 根据通知类型进行页面跳转
   if (notification.taskId && notification.taskType) {
     navigateToTask(notification.taskType, notification.taskId)
   }
 }

// 导航到任务页面
const navigateToTask = (_taskType: string, taskId: string) => {
  try {
    // 解析任务ID
    const [bookId, type, chapterNumber] = taskId.split('_')
    
    if (type === 'content') {
      // 章节内容生成任务
      router.push({
        path: '/book-workspace',
        query: { 
          id: bookId,
          tab: 'chapter',
          chapter: chapterNumber
        }
      })
    } else if (type === 'chapter') {
      // 章节生成任务
      router.push({
        path: '/book-workspace',
        query: { 
          id: bookId,
          tab: 'chapter'
        }
      })
    } else if (type === 'outline') {
      // 大纲生成任务
      router.push({
        path: '/book-workspace',
        query: { 
          id: bookId,
          tab: 'outline'
        }
      })
    } else if (type === 'analysis') {
      // 书籍分析任务
      router.push({
        path: '/book-analysis',
        query: { id: bookId }
      })
    }
  } catch (error) {
    console.error('导航到任务页面失败:', error)
    message.error('导航失败')
  }
}

// 获取任务类型标签
const getTaskTypeLabel = (taskType: string) => {
  switch (taskType) {
    case 'outline':
      return '大纲生成'
    case 'chapter':
      return '章节生成'
    case 'content':
      return '内容生成'
    case 'analysis':
      return '书籍分析'
    default:
      return '未知任务'
  }
}

// 格式化时间
const formatTime = (timeStr: string) => {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now.getTime() - time.getTime()
  
  // 小于1分钟
  if (diff < 60 * 1000) {
    return '刚刚'
  }
  
  // 小于1小时
  if (diff < 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 1000))}分钟前`
  }
  
  // 小于1天
  if (diff < 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (60 * 60 * 1000))}小时前`
  }
  
  // 小于7天
  if (diff < 7 * 24 * 60 * 60 * 1000) {
    return `${Math.floor(diff / (24 * 60 * 60 * 1000))}天前`
  }
  
  // 超过7天显示具体日期
  return time.toLocaleDateString()
}

// 初始化
onMounted(async () => {
  await fetchNotifications(1, true)
})
</script>

<style scoped>
.notification-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.notification-card {
  min-height: 600px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h2 {
  margin: 0;
  font-size: 20px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.loading-container,
.error-container,
.empty-container {
  padding: 40px 0;
}

.notification-list {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 0;
  border-bottom: 1px solid var(--n-border-color);
}

.total-count {
  color: var(--n-text-color-2);
  font-size: 14px;
}

.list-content {
  flex: 1;
  padding: 0;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  padding: 16px 0;
  border-bottom: 1px solid var(--n-border-color);
  transition: background-color 0.3s;
}

.notification-item:hover {
  background-color: var(--n-hover-color);
}

.notification-item.unread {
  background-color: var(--n-color-primary-info-pressed);
}

.item-left {
  display: flex;
  align-items: center;
  margin-right: 12px;
}

.notification-icon {
  margin-left: 12px;
}

.item-content {
  flex: 1;
  cursor: pointer;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.notification-title {
  margin: 0;
  font-size: 16px;
  font-weight: 500;
  color: var(--n-text-color-1);
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.notification-meta {
  display: flex;
  align-items: center;
  gap: 8px;
}

.notification-time {
  font-size: 12px;
  color: var(--n-text-color-3);
}

.notification-text {
  margin: 0 0 8px 0;
  color: var(--n-text-color-2);
  line-height: 1.5;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.notification-task {
  margin-top: 8px;
}

.item-actions {
  display: flex;
  flex-direction: column;
  gap: 8px;
  margin-left: 12px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  padding: 20px 0;
}
</style>